<?php

namespace App\Http\Controllers\V1\Upload;

use App\Events\V1\ImportExportEvent;
use App\Http\Requests\V1\ImportDataRequest;
use App\Models\V1\NewArrival;
use Illuminate\Http\Request;
use Jenssegers\Agent\Agent;
use Maatwebsite\Excel\Facades\Excel;
USE Log;
use Auth;

class NewArrivalExcelUploadController extends BaseExcelUploadController
{

    /**
     * 上传excel文件
     *
     * @param Request $request
     * @return array
     */
    public function uploadData(Request $request)
    {
        $response = $this->uploadExcel($request);

        return response()->json($response)->header('Content-Type', 'text/html;charset=utf-8');
    }

    //
    /**
     * 导入课程数据
     *
     * @param Request $request
     */
    public function importData(ImportDataRequest $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '迎新换届数据导入失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $this->validateImport($request);
            $filePath = $request->input('successFile');
            $fileExtension = $request->input('extension');

            Excel::load($filePath, function($reader) use ($fileExtension) {
                $reader->limitColumns(5);
                //忽略空的cells
                $reader->ignoreEmpty();
                $data = $reader->toArray();
                collect($data) -> flatMap(function($item) use ($fileExtension) {
                    $isOn = false;
                    if ($item[4] == 0) {
                        $isOn = false;
                    }else {
                        $isOn = true;
                    }
                    $insert_data = [
                        'code' => $item[0],
                        'enrollment_year' => $item[1],
                        'enrollment_term' => $item[2],
                        'enrollment_serial' => $item[3],
                        'isOn' => $isOn,
                    ];
                    if (!empty($item[0]) && !empty($item[3])) {
                        NewArrival::updateOrCreate(['code'=>$item[0]],$insert_data);
                    }

                });
            });

            $response['rspStatus'] = true;
            $response['rspMsg'] = [
                'type' => 'import',
                'msg' => '成功导入['.$request->input('successFile').']文件',
            ];
            event(new ImportExportEvent(Auth::user(), new Agent(), $request->getClientIp(), time(), $response['rspMsg']));

            return response()->json($response)->header('Content-Type', 'text/html;charset=utf-8');
        }
    }

    /**
     * 导出迎新换届数据文件
     *
     * @param Request $request
     */
    public function exportData(Request $request)
    {
        $clientIP = $request->getClientIp();

        $header = ['迎新代码', '招生年份', '招生学期', '招生序号', '当前启动(1:启动 0：不启动)'];
        $custodian = NewArrival::all(['code', 'enrollment_year','enrollment_term','enrollment_serial','isOn']);
        $cellDatas = [$header];
        foreach ($custodian as $item) {
            $cellData = [
                $item->code,
                $item->enrollment_year,
                $item->enrollment_term,
                $item->enrollment_serial,
                $item->isOn,
            ];
            array_push($cellDatas, $cellData);
        }

        Excel::create(iconv('UTF-8', 'GBK','迎新换届'), function ($excel) use ($cellDatas, $clientIP) {
            $excel->sheet('newarrival', function ($sheet) use ($cellDatas) {
                $sheet->rows($cellDatas);
            });

            $response['rspMsg'] = [
                'type' => 'export',
                'msg' => '成功下载[迎新换届]导出文件',
            ];
            event(new ImportExportEvent(Auth::user(), new Agent(), $clientIP, time(), $response['rspMsg']));
        })->export('xls');
    }


    /****
     * 下载模版
     * @param Request $request
     */
    public function downData(Request $request)
    {
        $clientIP = $request->getClientIp();

        $header = ['迎新代码', '招生年份', '招生学期', '招生序号', '当前启动(1:启动 0：不启动)'];
        $cellDatas = [$header];
        $cellData = ['201720180202','2017','2017-2018-2','2','1'];
        array_push($cellDatas, $cellData);
        Excel::create('迎新换届数据导入模版', function ($excel) use ($cellDatas, $clientIP) {
            $excel->sheet('newarrival', function ($sheet) use ($cellDatas) {
                $sheet->rows($cellDatas);
            });
            $response['rspMsg'] = [
                'type' => 'export',
                'msg' => '成功下载[迎新换届]模版文件',
            ];
            event(new ImportExportEvent(Auth::user(), new Agent(), $clientIP, time(), $response['rspMsg']));
        })->export('xls');
    }
}
